package com.newbee.sustainability.web.aop;

import com.alibaba.fastjson.JSON;
import com.newbee.sustainability.common.exception.ServiceException;
import com.newbee.sustainability.common.vo.ResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionHandle {
    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ResponseVo exceptionHandler(Exception e) {
        ResponseVo responseVo = new ResponseVo();
        if (e instanceof ServiceException) {
            // service 操作异常
            ServiceException serviceException = (ServiceException) e;
            responseVo.error(serviceException.getCode(), serviceException.getMessage());
            LOGGER.error("service exception: 【{}】", JSON.toJSONString(responseVo), e);
        } else {
            responseVo.error("9999", "系统异常");
            LOGGER.error("service exception: 【{}】", JSON.toJSONString(responseVo), e);
        }
        return responseVo;
    }
}
